import { CMSDOMAIN } from '@/http/api.js'

console.log('CMSDOMAIN',CMSDOMAIN.includes('test'))

const env = CMSDOMAIN.includes('test') ? 'test' : 'online'
console.log(env)
 
let cacheMap = new Map();
let timeoutDefault = 1200;

function isTimeout(name) {
  const data = cacheMap.get(name+env);
  if (!data) return true;
  if (data.timeout === 0) return false;
  const currentTime = Date.now();
  const overTime = (currentTime - data.createTime) / 1000;
  if (overTime > data.timeout) {
    cacheMap.delete(name+env);
    if (name.startsWith("_")) {
      try {
        uni.removeStorageSync(name+env);
      } catch (e) {
        console.log(e);
      }
    }
    return true;
  }
  return false;
}

class CacheCell {
  constructor(data, timeout) {
    this.data = data;
    this.timeout = timeout;
    this.createTime = Date.now();
  }
}

class MinCache {
  constructor(timeout) {
    try {
      const res = uni.getStorageInfoSync();
      res.keys && 
        res.keys.forEach(name => {
          try {
            const value = uni.getStorageSync(name+env);
            cacheMap.set(name+env, value);
          } catch (e) {
            console.log(e);
          }
        });
    } catch (e) {
      console.log(e);
    }
    timeoutDefault = timeout;
  }
  set(name, data, timeout = timeoutDefault) {
    const cachecell = new CacheCell(data, timeout);
    let cache = null;
    if (name.startsWith("_")) {
      try {
        uni.setStorageSync(name+env, cachecell);
        cache = cacheMap.set(name+env, cachecell);
      } catch (e) {
        console.log(e);
      }
    } else {
      cache = cacheMap.set(name+env, cachecell);
    }
    return cache;
  }
  get(name) {
    return isTimeout(name) ? null : cacheMap.get(name+env).data;
  }
  delete(name) {
    let value = false;
    if (name.startsWith("_")) {
      try {
        uni.removeStorageSync(name+env+env);
        value = cacheMap.delete(name+env);
      } catch (e) {
        console.log(e);
      }
    } else {
      value = cacheMap.delete(name+env);
    }
    return value;
  }
  has(name) {
    return !isTimeout(name);
  }
  clear() {
    let value = false;
    try {
      uni.clearStorageSync();
      cacheMap.clear();
      value = true;
    } catch (e) {
      console.log(e);
    }
    return value;
  }
  install(Vue) {
    Vue.prototype.$cache = this;
  }
}

export default new MinCache();
